/**
 * 文件上传
 * Created by mlr on 2016/9/6.
 */
var path = require('path')
    , fs   = require('fs')
    , formidable = require('formidable')
    , util = require('util')
    , config = require('config')
    , uploadConfig = config.get('SYS.upload')
    , upName       = config.get('SYS.upload.upName')
    , form_arg   = {
        uploadDir: uploadConfig.tempdirName,
        multiples: true,
        keepExtensions: true,
        maxFieldsSize: uploadConfig.limit
    };

exports = module.exports = function(req, res, next){
    req.clearTimeout();
    var form = new formidable.IncomingForm(form_arg);
    //上传完成后处理
    form.parse(req, function(err, fields, files) {
        if(err){
            if(err){ return res.send({err: 1, errMsg: err}); }
            console.log('parse error: ' + err);
        } else {
            var file;
            if(Object.prototype.toString.call(files[upName]) === '[object Array]') {
                file = files[upName][0];
            } else if(Object.prototype.toString.call(files[upName]) === '[object Object]') {
                file = files[upName];
            }
            var result;
            if (file && file.path) {
                var fileName = file.name;
                var _fileName = fileName.substring(0, file.name.lastIndexOf('.'));
                var appName = _fileName.split('_')[0];
                var newPath = path.join(uploadConfig.dirName, appName, fileName);
                if (!fs.existsSync(path.join(uploadConfig.dirName, appName))) {
                    fs.mkdirSync(path.join(uploadConfig.dirName, appName));
                }
                var oldPath = file.path;
                fs.renameSync(oldPath, newPath);
                if (fs.existsSync(oldPath)) {
                    fs.unlinkSync(oldPath);
                }
                result = {err: 0, file: { path: newPath, name: file.name }};
            } else {
                result = { err : 1, errMsg: 'fileUpload error!'}
            }
            res.writeHead(200, {'content-type': 'text/plain;charset=utf-8'});
            res.write('received upload:\n\n');
            res.end(util.inspect(result));
        }
    });
};
